<?php
/**
 * Created by IntelliJ IDEA.
 * User: yeran
 * Date: 2018/4/23
 * Time: 下午6:07
 */

namespace Payment\Client;


use Payment\CancelContext;
use Payment\Common\PayException;
use Payment\Config;

class OrderCancel {

    private static $supportChannel = [

        Config::TL_CHANNEL_LITE,
    ];

    /**
     * @var  CancelContext
     */
    protected static $instance;


    protected static function getInstance($channel, $config)
    {
        if (is_null(self::$instance)) {
            static::$instance = new CancelContext();

            try {
                static::$instance->initCancelHandler($channel, $config);
            } catch (PayException $e) {
                throw $e;
            }
        }

        return static::$instance;
    }

    /**
     * @param string $channel
     * @param array $config
     * @param array $metadata
     *
     * @return mixed
     * @throws PayException
     */
    public static function run($channel, $config, $metadata)
    {
        if (! in_array($channel, self::$supportChannel)) {
            throw new PayException('sdk当前不支持该支付渠道，当前仅支持：' . implode(',', self::$supportChannel));
        }

        try {
            $instance = self::getInstance($channel, $config);

            $ret = $instance->cancel($metadata);
        } catch (PayException $e) {
            throw $e;
        }

        return $ret;
    }
}